<?php

namespace App\Logics;


use App\Models\Event;
use App\Models\User;
use App\Models\UserAuth;
use App\Models\UserFan;
use App\Service\Base\Logic;
use Illuminate\Support\Facades\DB;

class UserAuthLogic extends Logic
{

    // 认证操作：学校+机构


    // 列表查询
    public function getLists($myUid)
    {
        $event = $this->getAuthWhere();
        $where = $event[0];
        $bang  = $event[1];

        // 推荐
        $opt   = $this->option();
        $page  = $opt->getData('page', 0, 'intval');
        $rows  = $opt->getData('rows', 15, 'intval');
        $lists = $this->getAuth($where, $bang, $page, $rows);
        if(empty($page)){
            $lists = $this->followLists($lists, $myUid);  // 是否关注
        } else{
            $lists['list'] = $this->followLists($lists['list'], $myUid);  // 是否关注
        }

        return $lists;
    }

    // 学校+机构列表
    // 学校+机构推荐
    public function getPropose($auth_type = '', $number = 4, $myUid = 0)
    {
        $event = $this->getAuthWhere();
        $where = $event[0];
        $bang  = $event[1];

        // 推荐
        $bang[]  = 'is_propose';
        $bang[]  = 'verify';
        $where[] = ['is_propose', '=', 1];
        $where[] = ['verify', '=', 1];
        if($auth_type){
            $bang[]  = 'auth_type';
            $where[] = ['auth_type', '=', $auth_type];
        }


        $lists = $this->getAuth($where, $bang, 0, $number);
        $lists = $this->followLists($lists, $myUid);  // 是否关注

        return $lists;
    }

    // 获取认证资料
    // 学校+机构详情
    //    返回该学校+机构的最新活动，最新文章
    public function onShow($auth_id = 0, $myUid = 0)
    {
        $auth_id = $auth_id ?: $this->option()->getData('auth_id', 0, 'intval');
        if(empty($auth_id)){
            return $this->_returnFail('请指定要查看的记录！');
        }

        $model = new UserAuth();
        $info  = $model->isCache(true)->oneFind(['id' => $auth_id]);
        if($info){
            $info['user'] = (new User())->isCache(true)->oneFind(['id' => $info['uid']]);
        }

        // 判断是否关注
        $info['is_follow'] = (new UserFan())->isFollow($myUid, $auth_id);

        return $info;
    }

    // 执行认证操作
    public function onAuth($myUid)
    {
        $option = $this->option();
        $_type  = $option->getData('auth_type', null, 'trim');
        $_allow = $option->getData('school_allow', null, 'trim');


        // 认证以前请先完善资料
        $userDb = new User();
        $info   = $userDb->where('id', $myUid)->first();
        $mobile = $info['mobile'];
        $option->throwIf(empty($mobile), '请先完善个人资料！');


        // 判断是否已经提交认证
        //$option->throwIf(empty($code), '请填写验证码！');
        $option->throwIf($info['verify'] == 1, '你已经通过认证审核！');
        $option->throwIf(empty($_type), '请选择认证类型！');
        $option->throwIf(($_type == 'school') && empty($_allow), '请学校请上传办学资质！');

        // 添加的数据
        $data = [
            'uid'          => $myUid,
            'auth_type'    => $_type,
            'auth_name'    => $option->getData("auth_name", null, "trim"),
            'cover'        => $option->getData("cover", null, "trim"),
            'city'         => $option->getData("city", null, "trim"),
            'address'      => $option->getData("address", null, "trim"),
            'lng'          => $option->getData("lng", null, "trim"),  // 经度
            'lat'          => $option->getData("lat", null, "trim"),  // 维度
            'grade'        => $option->getData("grade", null, "trim"),
            'telephone'    => $option->getData("telephone", null, "trim"),
            'description'  => $option->getData("description", null, "trim"),
            'license_img'  => $option->getData("license_img", null, "trim"),
            'school_allow' => $_allow,
            'is_pay'       => 0,
            'verify'       => 0,
            //'form_time'    => 0,
            //'end_time'     => 0,
            //'ctime'        => $opt->getData("ctime", null, "intval"),
            //'mtime'        => $opt->getData("mtime", null, "intval"),
        ];


        // 判断是否已经提交（可能重复提交） ->where('verify', 0)
        $authDb   = new UserAuth();
        $authInfo = $authDb->where('uid', $myUid)->first();
        if($authInfo){
            $option->throwIf($authInfo['verify'] == 1, '你已经通过认证审核！');
            $option->throwIf($info['is_auth'] && ($authInfo['verify'] == 0), '你已经申请认证,请等待审核！');
            //$option->throwIf($authInfo['verify'] == 1, '你已经申请认证，请等待审核！');
            //$option->throwIf(($authInfo['verify'] == 0) && ($authInfo['end_time'] > LARAVEL_TIME), '你已经申请认证,请等待审核！');
        } else{
            $option->throwIf($info['is_auth'], '你已经申请认证,请等待审核！');
        }


        // 判断验证码
        //$smsDb = new SiteSms();
        //$where = ['mobile' => $mobile, 'code' => $code, "status" => "0"];
        //$sinfo = $smsDb->where($where)->orderBy("id", "DESC")->first();
        //$this->throwIf(empty($sinfo), '验证码错误！！');
        //$this->throwIf(LARAVEL_TIME - $sinfo->ctime > 600, '验证码超时！！');

        // 验证信息
        $rules  = ["auth_name" => 'required', "license_img" => 'required', "cover" => 'required', "realname" => 'required', "position" => 'required', "areas" => 'required', "files" => 'required', "job_time" => 'required',];
        $rules  = ["auth_name" => 'required', "license_img" => 'required', "cover" => 'required',];
        $msg    = ["auth_name" => '认证名称', "license_img" => '营业执照', "cover" => '封面图片',];
        $data   = $this->filterNull($data);
        $result = $userDb->validator($data, $rules, $msg);
        if($result === false){
            return $this->_returnFail($userDb->getError());
        }

        // 审核内容
        //$this->baiduTextCensor($data);

        // 保存
        $authDb = new UserAuth();
        $res    = $authDb->onAuth($myUid, $data);
        if($res === false){
            return $this->_returnFail($authDb->getError());
        }

        return true;
    }

    // 删除认证操作：用于再次测试
    public function delAuth($myUid)
    {
        // 数据
        $user = ['auth_name' => '', 'auth_type' => '', 'is_auth' => 0, 'verify' => 0, 'auth_time' => 0, 'end_time' => 0, 'auth_id' => 0];
        $data = [
            'auth_type'    => '',
            'auth_name'    => '',
            'city'         => '',
            'address'      => '',
            'cover'        => '',
            'lng'          => 0,
            'lat'          => 0,
            'form_time'    => 0,
            'end_time'     => 0,
            'grade'        => '',
            'telephone'    => '',
            'description'  => '',
            'license_img'  => '',
            'school_allow' => '',
            'times'        => 0,
            'is_pay'       => 0,
            'verify'       => 0,
        ];


        // 保存
        $authDb = new UserAuth();
        $userDb = new User();
        $info   = $authDb->where('uid', $myUid)->first();
        if(empty($info)){
            return $this->_returnFail('你暂时未进行认证操作！');
        }

        // 保存信息
        $info->fill($data);
        DB::beginTransaction();
        try{
            $result = $info->save();
            // 改变用户信息
            $result = $userDb->where(['id' => $myUid])->update($user);

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->_returnFail($e->getMessage());
        }

        $user['id'] = $myUid;
        $userDb->deleteCacheShow($user);
        $authDb->deleteCacheShow($data, $info);

        return true;
    }

    ##############################################################################
    // 查询列表
    public function getAuth($where, $bang, $page = 0, $rows = 15)
    {
        // 模型
        $start = $page ? ($page - 1) * $rows : 0;
        $model = new UserAuth();

        // 执行
        /*$KCache = $model->cacheKey('lists', $where);
        $result = $model->cacheClass()->getCache($KCache);
        if(empty($result)){}*/
        if($page){
            $result = $model->bangField($bang)->listPage($where, $page, $rows, "id DESC");
        } else{
            $result = $model->bangField($bang)->getList($where, $rows, "id DESC", $start);
        }


        return $result;
    }

    // 是否关注
    protected function followLists($lists, $myUid)
    {
        if(empty($lists)){
            return $lists;
        }

        $eventDb = new Event();
        $fanDb   = new UserFan();
        // 活动量
        $eventNos = $eventDb->selectRaw('auth_id, count(*) number')->where('is_sale', 1)->where('verify', 1)->groupBy(['auth_id'])->get()->toArray();
        $eventNos = array_column($eventNos, null, 'auth_id');
        foreach($lists as &$_row){
            $_row['event_no'] = $eventNos[$_row['id']]['number'] ?? 0;
            if($myUid){
                $_row['is_follow'] = $fanDb->isFollow($myUid, $_row['id']);
            } else{
                $_row['is_follow'] = 0;
            }
        }

        return $lists;
    }


    // 列表查询条件
    protected function getAuthWhere()
    {
        $option  = $this->option();
        $where   = [];
        $bang    = [];
        $a_id    = $option->getData('auth_id', 0, 'intval');
        $c_id    = $option->getData('course_id', 0, 'intval');
        $uid     = $option->getData('uid', 0, 'intval');
        $_type   = $option->getData('auth_type', null, 'trim');
        $grade   = $option->getData("grade", null, "trim");
        $_verify = $option->getData('verify', null, 'intval');
        $name    = $option->getData('auth_name', null, 'trim');
        $is_prop = $option->getData('is_propose', null, 'intval');  // 推荐
        $keyword = $option->getData('keyword', null, 'trim');
        if($a_id){
            $bang[]  = 'auth_id';
            $where[] = ['auth_id', '=', $a_id];
        }
        if($c_id){
            $bang[]  = 'course_id';
            $where[] = ['course_id', '=', $c_id];
        }
        if($uid){
            $bang[]  = 'uid';
            $where[] = ['uid', '=', $uid];
        }
        if(!is_null($_verify)){
            $bang[]  = 'verify';
            $where[] = ['verify', '=', $_verify];
        } else{
            $bang[]  = 'verify';
            $where[] = ['verify', '=', 1];
        }
        if(!is_null($_type)){
            $bang[]  = 'auth_type';
            $where[] = ['auth_type', '=', $_type];
        }
        if($grade){
            $bang    = 'grade';
            $where[] = ['grade', '=', $grade];
        }
        if($name){
            $bang    = false;
            $where[] = ['auth_name', 'like', "%".$name."%"];
        }
        if(!is_null($is_prop)){
            $bang[]  = 'is_propose';
            $where[] = ['is_propose', '=', $is_prop];
        }

        return [$where, $bang];
    }

}


